
layui.define(['jquery', 'layer', 'layim', "RongIMLib", 'laytpl', 'FileUtil', 'RongIMEmoji'], function(exports) { //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
    var $ = layui.jquery,
        RongIMLib = layui.RongIMLib,
        layer = layui.layer,
        layim = layui.layim,
        tpl = layui.laytpl,
        FileUtil = layui.FileUtil,
        allUser = {},
        initData = {};
    var events = {};
    var emit = function(event, data) {
        data && (events[event] ? events[event](data) : log(data));
    }
    var log = function(msg) {
        conf.log && console.log(msg);
    }

    var conf = {
        tokenId: '',
        layimOption: {},
        mine: {}, //当前用户
        log: 1, //是否将没有处理的监听事件的消息打印日志信息
        authPayloadUrl: '/api/im/account/getLogin',
        flag: 0, //是否启用消息记录漫游，默认 0 否，1 是
        is_md5: 0, //密码是否是 MD5 密码，默认否
        debugFlag: 0, //JMessage是否开启 Debug 模式
        isTry: 1, //第三方平台初始化失败，是否出现重试询问框
        saveMsgUrl: '/api/im/message/save', //保存消息路径
        autoSaveCount: 10000, //自动更新已读时间间隔
        isCustomerCare: false, //是否为客服模式
        refreshStatusCount: 30000, //刷新在线状态间隔
        prefix: '' //项目名前缀
    }

    var t, tp = ["{{# layui.each(d, function(index, item){ if(item.mine){ }}", '<li class="layim-chat-mine">', '<div class="layim-chat-user"><img src="{{ item.avatar }}">', "<cite><i>{{ layui.data.date(item.timestamp) }}</i>{{ item.username }}</cite>", "</div>", '<div class="layim-chat-text">{{ layui.layim.content(item.content) }}</div>', "</li>", "{{# } else { }}", "<li>", '<div class="layim-chat-user"><img src="{{ item.avatar }}">', "<cite>{{ item.username }}<i>{{ layui.data.date(item.timestamp) }}</i></cite>", "</div>", '<div class="layim-chat-text">{{ layui.layim.content(item.content) }}</div>', "</li>", "{{# } }); }}"].join(""),
        pageTp = ['<span class="ws-pre  {{# if(d.isLastPage){ }} ws-disable-btn {{# } }}" layim-event="prePage" ws-data="{{d.nextPage}}">', '<i class="layui-icon">&#xe603;</i>', "</span>", '<span class="ws-next {{#if(d.isFirstPage){ }} ws-disable-btn {{# } }}" layim-event="nextPage" ws-data="{{d.prePage}}">', '<i class="layui-icon">&#xe602;</i>', "</span>"].join(""),
        handOverTp = ['<ul class="ws-kufu-list">', "{{#layui.each(d.data,function(index,item){}}", '<li class="layer-clear">', '<div class="left">{{item.nickname}}</div>', '<div class="right">', '<button class="ws-handover-btn" layim-event="doHandOver" kefuId="{{item.username}}" kefuNickName="{{item.nickname}}">转接</button>', "</div>", "</li>", "{{#", "})", "}}", '{{#if(!d.data.length){ }}<li class="empty-kufu-list">暂无其他在线客服</li>{{# } }}', "</ul>"].join(""),
        WSIM = {
            config: function(options) {
                conf = $.extend(conf, options);
                $.ajaxSetup({
                    headers: {
                        'access-token': conf.tokenId
                    },
                });
                im.init();
            },
            on: function(event, callback) {
                events[event] ? '' : events[event] = callback;
            },
        }

    var im = {
    	/**
    	 * 聊天初始化
    	 */
        init: function() {
            layim.prefix=conf.prefix;
            im.register();
            im.mine();
        },
		/**
		 * Layui IM聊天页面操作事件注册
		 */
        register: function() {
        	/**
        	 * IM UI加载完成
        	 */
        	layim.on('ready', function() {
            	console.log('IM UI ready');
                im.autoSave();
                im.refreshStatus();
            });
            /**
             * 添加会话
             */
            layim.on('addConversation', function(i, callback) {
                im.addConversationNew(i, callback);
            });
            /**
             * 设置消息内容
             */
            layim.on('setMsg', function(res, X) {
                //内容转换
                var con = res.content;
                if (con) {
                    var type = !(con.match(/(\w+)[(\[]{1}/)) ? '' : con.match(/(\w+)[(\[]{1}/);
                    type = type[type.length - 1];
                    if (type === 'img') {
                        con = '[图片]';
                    } else if (type === 'file') {
                        con = '[文件]';
                    } else if (type === 'audio') {
                        con = '[音频]';
                    } else if (type === 'video') {
                        con = '[视频]';
                    } else {
                        con = con.replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function(i) {
                            var a = (i.match(/a\(([\s\S]+?)\)\[/) || [])[1],
                                e = (i.match(/\)\[([\s\S]*?)\]/) || [])[1];
                            return a ? a : i
                        });
                    }
                    con = con.replace(/&(?!#?[a-zA-Z0-9]+;)/g, "&amp;")
                        .replace(/</g, "&lt;").replace(/>/g, "&gt;")
                        .replace(/'/g, "&#39;").replace(/"/g, "&quot;")
                        .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2')
                        .replace(/face\[([^\s\[\]]+?)\]/g, function(i) {
                            var a = i.replace(/^face/g, "");
                            return '<img alt="' + a + '" title="' + a + '" src="' + X[a] + '">'
                        });
                     con = RongIMLib.RongIMEmoji.emojiToHTML(con);    
                        
                    if (window.tempEmojiPicker || window.emojiPicker) {
                        con = (window.tempEmojiPicker && window.tempEmojiPicker.unicodeToImage(con)) || (window.emojiPicker && window.emojiPicker.unicodeToImage(con));
                    } else {
                        im.initEmojiPicker(function() {
                            con = window.tempEmojiPicker.unicodeToImage(con);
                        })
                    }
                   
                };
                (!conf.isCustomerCare && $(".layim-list-history .layim-" + res.type + res.id + ">p").html(con)) || ($(".ws-history .layim-" + res.type + res.id + ">p").html(con));
            });  
            
            /**
             * 加载聊天记录
             */
            layim.on('loadChatLog', function(i, j, callback) {
                l = {
                    data: i,
                    base: j.base,
                };
                var cache = layui.layim.cache(),
                    local = layui.data('layim')[cache.mine.id];
                    

                var history = (local.history && local.history[i.type + i.id]) || "";
                if (history === '' && !conf.isCustomerCare) {
                    im.addConversation(i, function(sessionKey) {
                        $.ajax({
                            type: "GET",
                            async: false,
                            url: "/api/im/message/" +conf.mine.uid + '/' + sessionKey + "/1/20" ,
                            contentType: "application/json",
                            success: function(data) {
                                var mine = layui.layim.cache().mine;
                                l.local = im.syncChatLog(data.data, i, mine);
                                callback(l);
                            },
                            error: function(data) {
                                console.log(data);
                            }
                        });
                    });
                } else {
                    var sessionKey = conf.isCustomerCare ? i.sessionKey : local.history[i.type + i.id].sessionKey;
                    $.ajax({
                        type: "GET",
                        url: "/api/im/message/" +conf.mine.uid + '/' + sessionKey + "/1/20" ,
                        contentType: "application/json",
                        success: function(data) {
                            var mine = layui.layim.cache().mine;
                            l.local = im.syncChatLog(data.data, i, mine);
                            callback(l);
                        },
                        error: function(data) {
                            console.log(data);
                        }
                    });
                }
            });  
            
            /**
             * 监听发送消息    
             */
            layim.on('sendMessage', function(res, m, callback) {
                var mine = res.mine,
                    to = res.to,
                    type = res.msgType, //消息类型
                    conversationType = to.type, //对话类型个人、群聊 
                    con = mine.content;
                	msg = {
                		sessionType: conversationType,
                		senderId: conf.mine.uid,
                		receiverId: to.id,
                		sessionKey: to.sessionKey
                	};
                	if (conf.isCustomerCare) {
	                    msg.extra = conf.mine.kefuGroupId;
	                }
                // var type = !(con.match(/(\w+)[(\[]{1}/)) ? '' : con.match(/(\w+)[(\[]{1}/);
                // type = type[type.length - 1];
                if (conversationType === 'friend' || conversationType === 'CUSTOMER_SERVICE') {
                    msg.target_username = to.id;
                    msg.target_nickname = to.username;
                    
                    if (conf.isCustomerCare) { msg.msgExtra = to.extra };
                    if ('images' === type) {
                        msg.image = m.data.Location;
                        msg.content = m.data.Location;
                        msg.type = 'IMAGE';
                        im.sendSinglePic(msg, m, res, callback);
                    } else if ('file' === type) {
                        msg.file = im.getFormData();
                        im.sendSingleFile(msg, m, res, callback);
                    } else if ('audio' === type) {

                    } else if ('video' === type) {

                    } else if ('text' === type) {
                    	msg.type = 'TEXT';
                        msg.content = con;
                        im.sendSingleMsg(msg, res, callback);
                    } else if ('notification' === type) {
                        msg.custom = con;
                        im.sendSingleCustom(msg);
                    }
                } else {
                    msg.target_gid = to.id;
                    msg.gId = to.gId;
                    msg.target_gname = to.groupname;
                    if ('image' === type) {
                        msg.image = im.getFormData();
                        im.sendGroupPic(msg, m, res, callback);
                    } else if ('file' === type) {
                        msg.file = im.getFormData();
                        im.sendGroupFile(msg, m, res, callback);
                    } else if ('audio' === type) {

                    } else if ('video' === type) {

                    } else if ('text' === type) {
                        msg.content = con;
                        im.sendGroupMsg(msg, res, callback);
                    } else if ('notification' === type) {

                    }
                }
            });  
          	/**
          	 * 刷新会话列表
          	 */
            layim.on('refreshHistory', function(callback) {
                if (!conf.isCustomerCare) {
                    im.history(callback);
                } else {
                    im.historyEx(callback);
                }
            });
            
            
            //查询同组下的在线客服列表
            layim.on('getCustomerCareList', function(callback) {
                var mine = conf.mine || {},
                    groupid = mine.kefuGroupId || 1;
                $.ajax({
                        url: '/api/im/cusService/online/all/' + groupid,
                        type: 'GET'
                    })
                    .done(function(res) {
                        if (0 == res.meta.code) {
                            tpl(handOverTp).render(res, function(html) {
                                callback(html)
                            });
                        } else {

                        }
                    })
                    .fail(function(res) {
                        console.log("error");
                    });
            });
            layim.on('doHandOver', function(kefuId, u, callback) {
                var obj = {
                    customerService: kefuId,
                    customer: u.id
                }
                $.ajax({
                        url: '/api/im/cusService/change',
                        type: 'POST',
                        contentType: "application/json",
                        data: JSON.stringify(obj)
                    })
                    .done(function(res) {
                        if (0 == res.meta.code) {
                            callback(u, 0);
                        } else {
                            callback(u, 90001);
                        }
                    })
                    .fail(function(res) {
                        callback(u, -1);
                    });
            });
            // 获取项目名   
            layim.on('getPrefix', function(callback) {
                callback(layim.prefix);
            });

            //刷新好友列表
            layim.on('refreshFriend', function(callback) {
                im.friend(callback);
            });
            //刷新群组
            layim.on('refreshGroup', function(callback) {
                im.group(callback);
            });
            //加好友
            layim.on('addFriend', function(data, callback) {
                im.addFriend(data, callback);
            });

            //消息盒子请求添加tokenId参数
            layim.on('setTokenId', function(callback) {
                callback(conf.tokenId);
            });

            //记录查看信息后的时间
            layim.on('closeLog', function(res) {
                var cache = layui.layim.cache(),
                    local = layui.data('layim')[cache.mine.id];
                local.logs = local.logs || {};
                local.logs[res] = (new Date).getTime();
                layui.data('layim', {
                    key: cache.mine.id,
                    value: local
                });
            });
            //这是所有窗口关闭
            layim.on('closeAll', function(res) {
                var cache = layui.layim.cache(),
                    local = layui.data('layim')[cache.mine.id];
                local.logs = local.logs || {};
                local.logs[res] = (new Date).getTime();
                layui.data('layim', {
                    key: cache.mine.id,
                    value: local
                });
                im.updateSesionDate();
            });
            //适配查看群成员接口
            layim.on('getMembers', function(i, callback) {
                $.ajax({
                    type: "get",
                    url: '/api/im/group/' + i.data.gId + '/members/1/999',
                    success: function(res) {
                        if (res.meta.code == 0) {
                            var data = {};
                            data.code = res.meta.code;
                            data.message = res.meta.message;
                            data.list = (res && res.data && res.data.list.length) ? im.dataToMembers(res) : [];
                            callback(data);
                        } else {
                            layer.msg('群成员信息获取失败！');
                        }
                    },
                    error: function(res) {
                        layer.msg('群成员信息获取出错');
                    }
                });
            });
            //窗口变化时触发的事件
            layim.on('chatChange', function(obj) {
                layim.activeId = obj.data.id || '';
                var res = obj.data;

                //清空会话列表的未读数
                var o1 = (!conf.isCustomerCare && $(".layim-list-history .layim-" + res.type + res.id + " span:last-child")) || ($(".ws-history .layim-" + res.type + res.id + " span:last-child")),
                    n1 = Number(o1.text());
                o1.text("");
                o1.removeClass("layui-badge ws-unread");
                //清空多人聊天时的未读数
                var o2 = $("#layui-layim-chat ul.layim-chat-list li.layim-" + res.type + res.id + " label");
                o2.text("");
                o2.removeClass('layui-badge');

                var cache = layui.layim.cache(),
                    local = layui.data('layim')[cache.mine.id];
                local.logs = local.logs || {};
                if (n1) {
                    local.logs[res.sessionId] = (new Date).getTime();
                    layui.data('layim', {
                        key: cache.mine.id,
                        value: local
                    });
                };

            });
            //设置未读数加一
            layim.on('setUnread', function(res) {
                //在会话列表中设置未读数
                var o1 = (!conf.isCustomerCare && $(".layim-list-history .layim-" + res.type + res.id + " span:last-child")) || ($(".ws-history .layim-" + res.type + res.id + " span:last-child")),
                    n1 = isNaN(Number(o1.text())) ? '99+' : Number(o1.text()) + 1;
                o1.text(n1);
                o1.addClass("layui-badge ws-unread");
                //在多人聊天设置未读数
                var o2 = $("#layui-layim-chat ul.layim-chat-list li.layim-" + res.type + res.id + " label"),
                    n2 = isNaN(Number(o2.text())) ? '99+' : Number(o2.text()) + 1;
                o2.text(n2);
                o2.addClass('layui-badge');

            });


            //文件上传完成数据格式转换
            layim.on('uploadComplete', function(res, callback) {
            	if(res.statusCode === 200) {
            		var i = {
                        "code": 0, //0表示成功，其它表示失败
                        "msg": 'success', //失败信息
                        "data": {
                            "src": res.Location, //url
                            "name": '文件名' //文件名
                        }
                    }
            	} else {
            		var i = {
                        "code": -1, //0表示成功，其它表示失败
                        "msg": 'fail', //失败信息
                        "data":{}
                    }
            	}
                callback(i);
            });

            //删除会话信息
            layim.on('delSession', function(h, callback) {
                if (h && h.sessionId) {
                    $.ajax({
                            url: '/api/im/session/' + h.sessionId,
                            type: 'DELETE',
                            contentType: 'application/json'
                        })
                        .done(function(res) {
                            if (res.meta.code == '0') {
                                callback();
                            } else {
                                layer.msg("移除会话失败");
                            }
                        })
                        .fail(function(res) {
                            layer.msg("移除会话出错");
                        });
                } else {
                    //移除所有会话
                    $.ajax({
                            url: '/api/im/session',
                            type: 'DELETE',
                            contentType: 'application/json'
                        })
                        .done(function(res) {
                            if (res.meta.code == '0') {
                                callback();
                            } else {
                                layer.msg("移除所有会话失败");
                            }
                        })
                        .fail(function(res) {
                            layer.msg("移除所有会话出错");
                        });
                }
            });
            //查看更多聊天记录
            layim.on('viewChatLog', function(data) {
                im.listChatLog(data, 1);
            });
            //查看更多聊天记录前一页
            layim.on('prePage', function(i, j) {
                if (!i.hasClass('ws-disable-btn')) {
                    im.listChatLog(j, Number(i.attr("ws-data")));
                }

            });
            //查看更多聊天记录后一页
            layim.on('nextPage', function(i, j) {
                if (!i.hasClass('ws-disable-btn')) {
                    im.listChatLog(j, Number(i.attr("ws-data")));
                }

            });
        },   
		/**
		 * 获取个人信息
		 */
        mine: function() {
            conf.mine.avatar = conf.mine.avatar || layui.cache.dir + "css/modules/layim/img/default.png";
            initData.mine = conf.mine;
            //收集所有用户信息
            allUser[initData.mine.id] = conf.mine;
            layim.allUser = allUser;
            im.initRong();
        },    
 		/**
		 * 获取IM服务器配置信息
		 * @param {Object} callback
		 */
        getAuthPaylad: function(callback) {
            if (!conf.authPayloadUrl) {
                console.log('请检查config.authPayloadUrl配置');
                return;
            }
            $.ajax({
                type: "get",
                url: conf.authPayloadUrl,
                success: function(res) {
                    // console.log(res)
                    if(res.meta){
                        if (res.meta.code == 0) {
                            res.data.flag = conf.flag;
                            callback(res.data);
                        } else {
                            layer.msg('获取连接通讯平台身份凭证失败');
                        }
                    }
                },
                error: function(res) {
                    layer.msg('获取连接通讯平台身份凭证出错');
                }
            });
        }, 
		/**
         * 初始化融云
         */
        initRong: function() {
            im.getAuthPaylad(function(t) {
            	let appkey = t.appKey;
            	RongIMLib.RongIMClient.init(appkey);
            	im.registeRongEvent();
            	im.login(initData.mine.uid);
            });
        },        
        /**
         * 注册融云事件
         */
        registeRongEvent() {
			// 设置连接监听状态 （ status 标识当前连接状态 ）
			// 连接状态监听器
			RongIMClient.setConnectionStatusListener({
		    	onChanged: function (status) {
			        switch (status) {
			            case RongIMLib.ConnectionStatus.CONNECTED:
			                console.log('链接成功');
			                break;
			            case RongIMLib.ConnectionStatus.CONNECTING:
			                console.log('正在链接');
			                break;
			            case RongIMLib.ConnectionStatus.DISCONNECTED:
			                console.log('断开连接');
			                break;
			            case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
			                console.log('其他设备登录');
			                break;
			              case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
			                console.log('域名不正确');
			                break;
			            case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
			              console.log('网络不可用');
			              break;
			            }
			}}); 
			
			// 消息监听器
			RongIMClient.setOnReceiveMessageListener({
			    // 接收到的消息
			    onReceived: function (message) {
			    	console.log('rong message received');
			    	console.log(message);
			        // 判断消息类型
			        switch(message.messageType){
			            case RongIMClient.MessageType.TextMessage:
			                // message.content.content => 消息内容  文本消息
			                im.handleReceiveContentMessage(message, 1);
			                break;
			            case RongIMClient.MessageType.VoiceMessage:
			                // 对声音进行预加载                语音消息
			                // message.content.content 格式为 AMR 格式的 base64 码
			                break;
			            case RongIMClient.MessageType.ImageMessage:
			               // message.content.content => 图片缩略图 base64。 图片消息
			               // message.content.imageUri => 原图 URL。
			               im.handleReceiveContentMessage(message, 2);
			               break;
			            case RongIMClient.MessageType.RichContentMessage:
			               // message.content.content => 文本消息内容。 图文消息
			               // message.content.imageUri => 图片 base64。
			               // message.content.url => 原图 URL。
			               break;
			            case RongIMClient.MessageType.LocationMessage:
			               // message.content.latiude => 纬度。  位置消息
			               // message.content.longitude => 经度。
			               // message.content.content => 位置图片 base64。
			               im.handleReceiveContentMessage(message, 3);
			               break;
			            case RongIMClient.MessageType.FileMessage:
			               // message.content.content => 文本消息内容。 文件消息
			               // message.content.imageUri => 图片 base64。
			               // message.content.url => 原图 URL。
			               im.handleReceiveContentMessage(message, 4);
			               break;
			            case RongIMClient.MessageType.SightMessage:
			               // message.content.content => 文本消息内容。 小视频消息
			               // message.content.imageUri => 图片 base64。
			               // message.content.url => 原图 URL。
			               break;
			            case RongIMClient.MessageType.PublicServiceRichContentMessage:
			               // message.content.content => 文本消息内容。 公众服务单图文消息
			               // message.content.imageUri => 图片 base64。
			               // message.content.url => 原图 URL。
			               break;
			            case RongIMClient.MessageType.PublicServiceMultiRichContentMessage:
			               // message.content.content => 文本消息内容。公众服务多图文消息
			               // message.content.imageUri => 图片 base64。
			               // message.content.url => 原图 URL。
			               break;
			            case RongIMClient.MessageType.ContactNotificationMessage:
			               // message.content.extension => 好友通知消息
			               break;
			            case RongIMClient.MessageType.ProfileNotificationMessage:
			                // do something...  ===>资料通知消息
			               break;
			            case RongIMClient.MessageType.CommandNotificationMessage:
			                // do something...   ====>通用命令通知消息
			               break;
			            case RongIMClient.MessageType.InformationNotificationMessage:
			                // do something...   ====>提示条通知消息
			               break;
			            case RongIMClient.MessageType.GroupNotificationMessage:
			                // do something...   ======>群组通知消息
			               break;
			            case RongIMClient.MessageType.ReadReceiptMessage:
			                // do something...   ====>已读通知消息
			               break;
			            case RongIMClient.MessageType.PublicServiceCommandMessage:
			                // do something...   ===>公众服务命令消息
			               break;
			            case RongIMClient.MessageType.CommandMessage:
			                // do something...   ===>命令消息
			               break;  
			            case RongIMClient.MessageType.TypingStatusMessage:
			                // do something...   ===>对方正在输入状态消息
			               break;  
			            default:
			                // do something...
			        }
			    }
			});			
        },
        /**
         * 
         * @param {Object} username
         * @param {Object} password
         */
        login: function(uid) {
			$.ajax({
                type: "get",
                url: '/api/im/account/'+uid+'/info',
                success: function(res) {
                    if (res.meta.code == 0) {
                        im.loginSuccess(res.data);
                    } else {
                        layer.msg('获取连接通讯平台身份凭证失败');
                    }
                },
                error: function(res) {
                    layer.msg('获取连接通讯平台身份凭证出错');
                }
            });        	
        },
        /**
         * 获取当前用户信息成功
         * @param {Object} data
         */
        loginSuccess: function(data) {
        	//1.IM连接
        	im.connect(data.imToken);
        	//2.设置用户信息
        	im.ininLayim();
        },
        /**
         * IM连接
         */
        connect: function(imToken) {
        	RongIMClient.connect(imToken, {
        		onSuccess: function(userId) {
          			console.log("Connect successfully." + userId);
        		},
        		onTokenIncorrect: function() {
          			console.log('token无效');
        		},
        		onError:function(errorCode){
              		var info = '';
              		switch (errorCode) {
                		case RongIMLib.ErrorCode.TIMEOUT:
                  			info = '超时';
                  			break;
                		case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
                  			info = '不可接受的协议版本';
                  			break;
                		case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                  			info = 'appkey不正确';
                  			break;
                		case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                  			info = '服务器不可用';
                  			break;
             	 	}
              		console.log(errorCode);
            	}
      		});        	
        },
        /**
         * 初始化IM聊天配置
         */
        ininLayim: function() {
            //采用多次获取初始化数据,覆盖一次获取数据
            conf.layimOption.init = initData;
            conf.layimOption.isfriend = true;
            conf.layimOption.isgroup = true;
            conf.layimOption.isHandOver = false;
            conf.layimOption.isCustomerCare = conf.isCustomerCare;
            conf.layimOption.chatLog = {};
            conf.layimOption.msgbox = layui.cache.dir + 'css/modules/layim/html/msgbox.html';
            conf.layimOption.uploadImage = {
                type: 'POST',
                url: '/api/batch/upload?access-token=' + conf.tokenId
            };
            conf.layimOption.uploadFile = {
                type: 'POST',
                url: '/api/batch/upload?access-token=' + conf.tokenId
            };

            //调用自动保存方法  
            //im.autoSave();
            var cache = layui.layim.cache() || {};
            cache.mine = cache.mine || initData.mine;
            var local = layui.data('layim')[cache.mine.id] || {};
            local.logs = null;
            local.history = null;
            layui.data('layim', {
                key: cache.mine.id,
                value: local
            });
            //基础配置
            layim.config(conf.layimOption);
        },
        /**
         * 自动更新客服已读消息状态
         */
        autoSave: function() {
            im.updateSesionDate();
            var t1 = window.setTimeout(im.autoSave, conf.autoSaveCount);
        },
        /**
         * 更新消息最后查看时间
         */
        updateSesionDate: function() {
            var cache = layui.layim.cache(),
                local = layui.data('layim')[cache.mine.id],
                data = local.logs;
            	data && (
                $.ajax({
                    url: '/api/im/session/markRead?uid=' + conf.mine.uid,
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(data)
                })
                .done(function(res) {
                    local.logs = null;
                    layui.data('layim', {
                        key: cache.mine.id,
                        value: local
                    });
                })
                .fail(function(res) {
                    console.log("error");
                })
            )
        },   
        /**
         * 刷新客服在线状态
         */
        refreshStatus: function() {
            im.refreshLoginStatus();
            var t2 = window.setTimeout(im.refreshStatus, conf.refreshStatusCount);
        }, 
        /**
         * 刷新客服在线状态
         */
        refreshLoginStatus: function() {
            $.ajax({
                    url: '/api/im/customer/service/refresh?uid=' + conf.mine.uid,
                    type: 'GET',
                })
                .done(function(res) {
                    if (0 != res.meta.code) {
                        emit('refreshLoginStatus', res);
                    }
                })
                .fail(function(res) {
                    emit('refreshLoginStatus', res);
                });

        },    
        /**
         * 历史消息
         * @param {Object} callback
         */
        historyEx: function(callback) {
            var cache, local, history = [];
            cache = layim.cache() || {};
            cache.mine = (!cache.mine ? initData.mine : cache.mine);
            local = layui.data('layim')[cache.mine.id] || {}; //获取当前用户本地数据            
            $.ajax({
                type: "GET",
                url: "/api/im/customer/service/session?uid=" + conf.mine.uid,
                success: function(res) {
                    if (res.meta.code == 0) {
                        data = res.data || {};
                        local.history = data ? im.dataToHistoryEx(data) : {};
                        //向localStorage同步数据
                        layui.data('layim', {
                            key: cache.mine.id,
                            value: local,
                        });
                        callback && callback(local.history);
                        $('.ws-list-history .ws-refresh').hide();
                    } else {
                        local.history = {};
                        //向localStorage同步数据
                        layui.data('layim', {
                            key: cache.mine.id,
                            value: local,
                        });
                        $('.ws-list-history .ws-refresh').find('.ws-error').text('加载会话失败').show();
                    }
                },
                error: function(res) {
                    local.history = {};
                    //向localStorage同步数据
                    layui.data('layim', {
                        key: cache.mine.id,
                        value: local,
                    });
                    $('.ws-list-history .ws-refresh').find('.ws-error').text('加载会话出错').show();
                }
            });
            callback && callback(local.history);
        },  
        dataToHistoryEx: function(data) {
            var history = [],
                allConversion = {},
                item1 = {},
                item2 = {},
                normal = data.normalSession || [],
                readOnly = data.readOnlySession || [],
                i = normal.length || 0,
                j = readOnly.length || 0;
            item1.id = 1;
            item1.groupname = '服务列表';              
            item1.online = 2;
            item1.list = [];
            while (i--) {
                var u = im.dataToUser(normal[i].user);
                u.type = 'CUSTOMER_SERVICE';
                u.unread = normal[i].unread;
                u.sessionKey = normal[i].sessionKey;
                u.sessionId = normal[i].id;
                u.extra = normal[i].extra;
                u.sign = normal[i].lastMessage ? im.dataToCon(normal[i].lastMessage) : '';
                u.groupId = 0;
                item1.list.push(u);
                allConversion[u.type + u.id] = u;
                allUser[u.id] = u;
                layim.allUser = allUser;
                layim.allConversion = allConversion;
            }
            item2.id = 2;
            item2.groupname = '服务历史';
            item2.online = 2;
            item2.list = [];
            while (j--) {
                var u = im.dataToUser(readOnly[j].user);
                u.type = 'CUSTOMER_SERVICE';
                u.unread = readOnly[j].unread;
                u.sessionKey = readOnly[j].sessionKey;
                u.sessionId = readOnly[j].id;
                u.extra = readOnly[j].extra;
                u.isView = true;
                u.sign = readOnly[j].lastMessage ? im.dataToCon(readOnly[j].lastMessage) : '';
                u.groupId = 1;
                item2.list.push(u);
                allConversion[u.type + u.id] = u;
                allUser[u.id] = u;
                layim.allUser = allUser;
                layim.allConversion = allConversion;
            }
            history.push(item1);
            //TODO 不添加服务历史
//          history.push(item2);

            return history;
        },        
        history: function(callback) {
            var data, cache, local;
            cache = layim.cache() || {};
            cache.mine = (!cache.mine ? initData.mine : cache.mine);
            local = layui.data('layim')[cache.mine.id] || {}; //获取当前用户本地数据
            $.ajax({
                type: "GET",
                url: "/ws/im/session",
                success: function(res) {
                    if (res.meta.code == 0) {
                        data = res.data || {};
                        local.history = (data && data.length) ? im.dataToHistory(data) : {};
                        //向localStorage同步数据
                        layui.data('layim', {
                            key: cache.mine.id,
                            value: local,
                        });
                        callback && callback(local.history);
                        $('.ws-list-history .ws-refresh').hide();
                    } else {
                        local.history = {};
                        //向localStorage同步数据
                        layui.data('layim', {
                            key: cache.mine.id,
                            value: local,
                        });
                        $('.ws-list-history .ws-refresh').find('.ws-error').text('加载会话失败').show();
                    }
                },
                error: function(res) {
                    local.history = {};
                    //向localStorage同步数据
                    layui.data('layim', {
                        key: cache.mine.id,
                        value: local,
                    });
                    $('.ws-list-history .ws-refresh').find('.ws-error').text('加载会话出错').show();
                }
            });
        },        
       	dataToHistory: function(data) {
            var history = {};
            var len = data.length;
            while (len--) {
                var t = (data[len].type === 'GROUP' ? 'group' : 'friend');
                if ('group' === t && data[len].group) {
                    var g = im.dataToGroupHistory(data[len].group, data[len].lastMessage);
                    g.type = t;
                    g.unread = data[len].unread;
                    g.sessionKey = data[len].sessionKey;
                    g.sessionId = data[len].id;
                    history[t + g.id] = g;
                } else if ('friend' === t && data[len].user) {
                    var u = im.dataToUser(data[len].user);
                    u.type = t;
                    u.unread = data[len].unread;
                    u.sessionKey = data[len].sessionKey;
                    u.sessionId = data[len].id;
                    u.sign = data[len].lastMessage ? im.dataToCon(data[len].lastMessage) : '';
                    history[t + data[len].user.username] = u;
                }

            }
            return history;
        },  
        dataToGroupHistory: function(data, msg) {
            g = {
                avatar: data.avatar || layui.cache.dir + "css/modules/layim/img/default.png",
                groupname: data.name,
                id: data.groupId,
                gId: data.id,
                name: data.name,
                sign: msg ? im.dataToCon(msg) : ''
            }
            return g;
        }, 
        /**
         * 处理融云收到的内容消息
         */
        handleReceiveContentMessage(data, msgType) {
        	var content_ = '';
        	var datatype_ = '';
        	switch(msgType) {
        		case 1: 
        			content_ = data.content.content;
        			datatype_ = 'TEXT';
        		break;
        		case 2:
        			content_ = "img[" + data.content.imageUri + "]";
        			datatype_ = 'IMAGE';
        		break;
        		case 3:
        		break;
        		case 4:
        		break;
        	}
        	let cacheUser = layim.allUser[data.senderUserId];
        	if(!cacheUser) {
        		cacheUser = im.getUserInfo(data.senderUserId);
        		layim.allUser[data.senderUserId] = cacheUser;
        	}
        	var layUIMsg = {
        		  username: cacheUser.username //消息来源用户名
				  ,avatar: cacheUser.avatar //消息来源用户头像
				  ,id: data.targetId //消息的来源ID（如果是私聊，则是用户id，如果是群聊，则是群组id）
				  ,type: data.conversationType == 1 ? "friend" : "group" //聊天窗口来源类型，从发送消息传递的to里面获取
				  ,content: content_ //消息内容
				  ,cid: data.messageId //消息id，可不传。除非你要对消息进行一些操作（如撤回）
				  ,mine: false //是否我发送的消息，如果为true，则会显示在右方
				  ,fromid: data.senderUserId //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
				  ,timestamp: data.sentTime //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
        		  ,datatype: datatype_
        	};
        	layim.getMessage(layUIMsg);        	
        },
        /**
         * 添加新会话
         * @param {Object} res
         * @param {Object} callback
         */
        addConversationNew: function(res, callback) {
            var mine = layui.layim.cache().mine || {},
                mineId = mine.id,
                kefuGroupId = mine.kefuGroupId;
            var c = {
                "name": mineId + " TO " + res.id,
                "type": conf.isCustomerCare ? 'CUSTOMER_SERVICE' : (res.type === 'group' ? "GROUP" : "PRIVATE")
            }
			c.createrId = conf.mine.uid;
            c.otherId = res.id;
            c.extra = kefuGroupId;
            $.ajax({
                type: "POST",
                url: "/api/im/session",
                data: JSON.stringify(c),
                contentType: "application/json",
                success: function(msg) {
                    if (msg.meta.code === 0) {
                        var cache = layui.layim.cache(),
                            local = layui.data('layim')[cache.mine.id];
                        local.history = local.history || {};
                        res.sessionKey = msg.data.sessionKey;
                        res.type = 'CUSTOMER_SERVICE';
                        res.sessionId = msg.data.id;
                        res.unread = 0;
                        if (!conf.isCustomerCare) {
                            res.extra = msg.data.extra;
                            local.history[res.type + res.id] = res;
                        } else {
                            local.history[0].list.push(res);
                        }
                        layui.data('layim', {
                            key: cache.mine.id,
                            value: local
                        });
                        callback((!conf.isCustomerCare && msg.data) || local.history);
                    } else {
                        layer.msg('创建会话失败');
                    }
                },
                error: function(msg) {
                    layer.msg('创建会话出错');
                }
            });
        },  
        /**
         * 初始化emoji表情选择
         * @param {Object} callback
         */
        initEmojiPicker: function(callback) {
            window.tempEmojiPicker = new EmojiPicker({
                emojiable_selector: '#temp',
                assetsPath: conf.prefix + '/static/EmojiPicker/lib/img'
            });
            window.tempEmojiPicker.discover();
            callback();
        },
        /**
         * 同步聊天记录
         * @param {Object} data
         * @param {Object} res
         * @param {Object} mine
         */
        syncChatLog: function(data, res, mine) {
            var users=data && data.accountInfo || [],
            messages=data.messages.list||[],
            logs = [],
            len1 = messages.length || 0,
            len2= users.length || 0;
            while(len2--){
                var u = im.dataToUser(users[len2]);
                allUser[u.id] = u;
                layim.allUser = allUser;
            }
            while (len1--) {
                var d = im.dataToLog(messages[len1], res, mine);
                logs.push(d);
            }
            var cache = layui.layim.cache(),
                local = layui.data('layim')[cache.mine.id];
            local.chatlog = local.chatlog || {};
            local.chatlog[res.type + res.id] = {};
            local.chatlog[res.type + res.id] = logs;
            layui.data('layim', {
                key: cache.mine.id,
                value: local
            });
            return local;
        },    
        /**
         * 数据库数据转换为聊天记录
         * @param {Object} data
         * @param {Object} other
         * @param {Object} mine
         */
        dataToLog: function(data, other, mine) {
            var con = data.data || "",
                c = '',
                u = {};
            if (data.type === 'TEXT') {
                c = con;
            } else if (data.type === 'IMAGE') {
                c = "img[" + con + "]";
            } else if (data.type === 'FILE') {
                c = "file(" + (data.data && data.data.filePath) + ")[" + data.data.name + "]";
            } else if (data.type === 'VOICE') {
                c = "audio[" + con + "]";
            } else if (data.type === 'LOCATION') {
                c = "[位置] " + data.data.addressLabel;
            }
            if (!layim.allUser[data.senderId]) {
                u = im.getUserInfo(data.senderId) || {};
            } else {
                u = layim.allUser[data.senderId] || {};
            }
            var d = {
                avatar: u.avatar || layui.cache.dir + "css/modules/layim/img/default.png",
                content: c,
                id: data.receiverId,
                mine: conf.isCustomerCare ? (data.senderId != other.id) : (data.senderId === mine.id),
                timestamp: (new Date(data.createDate).getTime()),
                type: (data.sessionType === 'GROUP' ? 'group' : 'friend'),
                username: u.username || '未获取到昵称',
                datatype: data.type
            }
            return d;
        },  
        /**
         * 发送文本消息
         * @param {Object} msg
         * @param {Object} res
         * @param {Object} callback
         */
        sendSingleMsg: function(data, res, callback) {
        	var content_ = data.content;
        	var msg = new RongIMLib.TextMessage({content: content_,extra:""});
 			var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
 			var targetId = data.target_username; // 目标 Id
 			RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
                onSuccess: function (message) {
                    //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                    console.log("Send successfully");
                    emit("satus", message);
                    im.saveMsg(data, res, callback);
                },
                onError: function (errorCode,message) {
                    var info = '';
                    switch (errorCode) {
                        case RongIMLib.ErrorCode.TIMEOUT:
                            info = '超时';
                            break;
                        case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                            info = '未知错误';
                            break;
                        case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                            info = '在黑名单中，无法向对方发送消息';
                            break;
                        case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                            info = '不在讨论组中';
                            break;
                        case RongIMLib.ErrorCode.NOT_IN_GROUP:
                            info = '不在群组中';
                            break;
                        case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                            info = '不在聊天室中';
                            break;
                        default :
                            info = x;
                            break;
                    }
                    console.log('发送失败:' + info);
                }
           	});
        	
        },
        /**
         * 发送单张图片
         * @param {Object} msg
         * @param {Object} m
         * @param {Object} res
         * @param {Object} callback
         */
        sendSinglePic: function(data, m, res, callback) {
			 /*
			     图片转为可以使用 HTML5 的 FileReader 或者 canvas 也可以上传到后台进行转换。
			
			     注意事项：
			         1、缩略图必须是 base64 码的 jpg 图。
			         2、不带前缀。
			         3、大小不得超过 100kb。
			   */
			var compressConfig = {
//				width: 200,
//				height: 200
			};
			FileUtil.readCompressBase64(m.data.localFile, compressConfig, function(base64Str) {
				base64Str = base64Str.replace('data:image/jpeg;base64,' , '');
				var imageUri = data.image; // 上传到自己服务器的 URL。
				var msg = new RongIMLib.ImageMessage({content:base64Str,imageUri:imageUri});
				var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
				var targetId = data.target_username; // 目标 Id
				RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
	                onSuccess: function (message) {
	                    //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
	                    console.log("Send successfully");
	                    emit("satus", message);
	                    im.saveMsg(data, res, callback);
	                },
	                onError: function (errorCode,message) {
	                    var info = '';
	                    switch (errorCode) {
	                        case RongIMLib.ErrorCode.TIMEOUT:
	                            info = '超时';
	                            break;
	                        case RongIMLib.ErrorCode.UNKNOWN_ERROR:
	                            info = '未知错误';
	                            break;
	                        case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
	                            info = '在黑名单中，无法向对方发送消息';
	                            break;
	                        case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
	                            info = '不在讨论组中';
	                            break;
	                        case RongIMLib.ErrorCode.NOT_IN_GROUP:
	                            info = '不在群组中';
	                            break;
	                        case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
	                            info = '不在聊天室中';
	                            break;
	                        default :
	                            info = x;
	                            break;
	                    }
	                    console.log('发送失败:' + info);
	                }
	            });
			});
			
        },
        /**
         *
         * @param {Object} m
         * @param {Object} data
         * @param {Object} callback
         */
        saveMsg: function(m, data, callback) {
            $.ajax({
                type: "post",
                url: conf.saveMsgUrl,
                data: JSON.stringify(m),
                contentType: "application/json",
                success: function(res) {
                    if (res.meta.code == 0) {
                        callback(0, data);
                        emit("satus", res);
                        //layer.msg('保存聊天记录成功');
                    } else {
                        callback(90001, data);
                        //layer.msg('保存聊天记录失败');
                    }
                },
                error: function(res) {
                    callback(-1, data);
                    emit("saveMsg", '保存聊天记录出错');
                    //layer.msg('保存聊天记录出错');
                }
            });
        },
        /**
         * 转换用户数据
         * @param {Object} data
         */
        dataToUser: function(data) {
            data = data || {};
            mine = {
                "username": data.nickname || '未获取到昵称',
                "id": data.username || '',
                "status": "online",
                "sign": data.signature,
                "avatar": data.avatar || layui.cache.dir + "css/modules/layim/img/default.png"
            }
            return mine;
        },  
        /**
         * 转换消息
         * @param {Object} msg
         */
        dataToCon: function(msg) {
            var type = msg.type,
                con = msg.data;
            if ('IMAGE' === type) {
                con = '[图片]';
            } else if ('FILE' === type) {
                con = '[文件]';
            } else if ('VOICE' === type) {
                con = '[音频]';
            } else if ('LOCATION' === type) {
                con = '[位置]';
            } else if ('CUSTOME' === type) {
                con = '[自定义消息]';
            } else {
                con = con.replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function(i) {
                    var a = (i.match(/a\(([\s\S]+?)\)\[/) || [])[1],
                        e = (i.match(/\)\[([\s\S]*?)\]/) || [])[1];
                    return a ? a : i
                });
            }
            
            con = con.replace(/&(?!#?[a-zA-Z0-9]+;)/g, "&amp;")
                .replace(/</g, "&lt;").replace(/>/g, "&gt;")
                .replace(/'/g, "&#39;").replace(/"/g, "&quot;")
                .replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;">$1</a>$2')
                .replace(/face\[([^\s\[\]]+?)\]/g, function(i) {
                    var a = i.replace(/^face/g, "");
                    return '<img alt="' + a + '" title="' + a + '" src="' + im.dataToEmoji[a] + '">'
                });
            if (window.tempEmojiPicker || window.emojiPicker) {
                con = (window.tempEmojiPicker && window.tempEmojiPicker.unicodeToImage(con)) || (window.emojiPicker && window.emojiPicker.unicodeToImage(con));
            } else {
                im.initEmojiPicker(function() {
                    con = window.tempEmojiPicker.unicodeToImage(con);
                })
            }
            return con;
        },
        dataToEmoji: function() {
            var i = ["[微笑]", "[嘻嘻]", "[哈哈]", "[可爱]", "[可怜]", "[挖鼻]", "[吃惊]", "[害羞]", "[挤眼]", "[闭嘴]", "[鄙视]", "[爱你]", "[泪]", "[偷笑]", "[亲亲]", "[生病]", "[太开心]", "[白眼]", "[右哼哼]", "[左哼哼]", "[嘘]", "[衰]", "[委屈]", "[吐]", "[哈欠]", "[抱抱]", "[怒]", "[疑问]", "[馋嘴]", "[拜拜]", "[思考]", "[汗]", "[困]", "[睡]", "[钱]", "[失望]", "[酷]", "[色]", "[哼]", "[鼓掌]", "[晕]", "[悲伤]", "[抓狂]", "[黑线]", "[阴险]", "[怒骂]", "[互粉]", "[心]", "[伤心]", "[猪头]", "[熊猫]", "[兔子]", "[ok]", "[耶]", "[good]", "[NO]", "[赞]", "[来]", "[弱]", "[草泥马]", "[神马]", "[囧]", "[浮云]", "[给力]", "[围观]", "[威武]", "[奥特曼]", "[礼物]", "[钟]", "[话筒]", "[蜡烛]", "[蛋糕]"],
                a = {};
            return layui.each(i, function(i, e) {
                a[e] = layui.cache.dir + "images/face/" + i + ".gif"
            }), a
        }(), 
        getUserInfo: function(id) {
            var u = {};
            $.ajax({
                type: "get",
                url: "/api/im/account/" + id + "/info",
                async: false,
            }).done(function(res) {
                u = res.data ? im.dataToUser(res.data) : {};
                allUser[id] = u;
                layim.allUser = allUser;
            }).fail(function(res) {

            });
            return u;
        },        
        
    }

    exports('WSIM', WSIM);
});